package com.xucy.springboot.concurrent.tools;

import java.util.concurrent.*;

/**
 * @Author xucy
 * @Date 2019-07-20 16:01
 * @Description
 **/

public class ExchangerTest {
    public static void main(String[] args) {
        ExecutorService executor = new ThreadPoolExecutor(2,2,0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        final Exchanger exchanger = new Exchanger();
        Future future=executor.submit(new Runnable() {
            String data1 = "Ling";

            @Override
            public void run() {
                doExchangeWork(data1, exchanger);
            }
        });

        Future future1=executor.submit(new Callable<String>() {
            String data2 = "Di";

            @Override
            public String call() {
                doExchangeWork(data2, exchanger);
                return "2323";
            }
        });

        try {
            System.out.println(future.get());
            System.out.println(future1.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        if(future.isDone()){
            System.out.println("线程1执行完了");

        }
        executor.shutdown(); //把线程池停掉 释放资源
    }

    private static void doExchangeWork(String data1, Exchanger exchanger) {
        try {
            System.out.println(Thread.currentThread().getName() + "正在把数据 " + data1 + " 交换出去");
            Thread.sleep((long) (Math.random() * 1000));

            String data2 = (String) exchanger.exchange(data1);
            System.out.println(Thread.currentThread().getName() + "交换数据 到  " + data2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
